<?php
namespace Controller;
use Kuyuan\WqCore\controller\Controller;
use Model\MchOrderModel;

/**
 * 微信商户订单
 * Class MchOrder
 * @package Controller
 */
class MchOrder extends Controller
{
    private $MchOrder = null;
    public function __construct()
    {
        parent::__construct();
        $this->MchOrder = new MchOrderModel();
    }

    /**
     * 创建微信商户订单
     * @param double $_money 订单金额
     * @param int $_source_id 支付源id
     * @param string $_source 支付源
     * @return bool|string
     */
    public function create($_money,$_source_id,$_source = 'red')
    {
        $_order_id = $this->createOrderId();
        $_data = array(
            "order_id" => $_order_id,
            "uniacid" => $this->_uniacid,
            "uid" => $this->_uid,
            "money" => $_money,
            "source" => $_source,
            "source_id" => $_source_id,
            "time" => TIMESTAMP
        );
        if(MchOrderModel::create($_data)) {
            return $_order_id;
        } else {
            return false;
        }
    }

    /**
     * 创建订单号id
     */
    private function createOrderId()
    {
        $_order_id = TIMESTAMP.mt_rand(10000,99999);
        if(MchOrderModel::where("order_id",$_order_id)->value("id")) {
            return $this->createOrderId();
        }
        return $_order_id;
    }

    /**
     * 根据支付源和支付源id获取一个微信支付商户本地订单详情
     * @param $_source_id
     * @param string $_source
     * @return mixed
     */
    public function find($_source_id,$_source = 'red')
    {
        return MchOrderModel::where("source_id",$_source_id)
                            ->where("source",$_source)
                            ->field(array("uid","order_id","money","status"))
                            ->cache(!KUYUAN_DEBUG)
                            ->find();
    }

    /**
     * 修改数据
     * @param int $_source_id 支付源id 红包id
     * @param array $_data
     * @param string $_source 支付源类型 red=发红包支付
     * @return mixed
     */
    public function edit($_source_id,Array $_data,$_source = 'red')
    {
        return $this->MchOrder->where("source_id",$_source_id)
            ->where("source",$_source)
            ->update($_data);
    }
}